//
//  View+Alert.swift
//  SomePasti
//
//  Created by 李永彬 on 2025/10/9.
//

import SwiftUI

// View 扩展 - 支持 dismiss 回调
extension View {
    
    // MARK: - Window 弹窗（完全自定义内容）
    func smCustomPopupOnWindow<Content: View>(
        isPresented: Binding<Bool>,
        style: SMPopupStyle = .alert,
        backgroundImage: String? = nil,
        onDismissCompleted: (() -> Void)? = nil, // 新增参数
        @ViewBuilder content: @escaping () -> Content
    ) -> some View {
        let config = SMPopupConfig(
            style: style,
            backgroundImage: backgroundImage,
            animation: .spring(response: 0.3, dampingFraction: 0.8)
        )
        
        return self.onChange(of: isPresented.wrappedValue) { newValue in
            print("弹窗状态变化: \(newValue)")
            if newValue {
                SMWindowPopupManager.shared.showPopup(
                    isPresented: isPresented,
                    config: config,
                    onDismissCompleted: onDismissCompleted, // 传递回调
                    content: content
                )
            } else {
                SMWindowPopupManager.shared.dismissPopup(for: isPresented)
            }
        }
    }
    
    // MARK: - Window 标准弹窗
    func smAlertOnWindow(
        isPresented: Binding<Bool>,
        title: String,
        message: String? = nil,
        backgroundImage: String? = nil,
        onDismissCompleted: (() -> Void)? = nil, // 新增参数
        buttons: [SMPopupButton]
    ) -> some View {
        let standardView = SMPopupStandardView(
            title: title,
            message: message,
            backgroundImage: backgroundImage,
            buttons: buttons
        )
        
        return self.smCustomPopupOnWindow(
            isPresented: isPresented,
            style: .alert,
            backgroundImage: backgroundImage,
            onDismissCompleted: onDismissCompleted // 传递回调
        ) {
            standardView
        }
    }
    
    // MARK: - Window ActionSheet
    func smActionSheetOnWindow(
        isPresented: Binding<Bool>,
        title: String? = nil,
        message: String? = nil,
        backgroundImage: String? = nil,
        onDismissCompleted: (() -> Void)? = nil, // 新增参数
        buttons: [SMPopupButton]
    ) -> some View {
        let standardView = SMPopupStandardView(
            title: title,
            message: message,
            backgroundImage: backgroundImage,
            buttons: buttons
        )
        
        return self.smCustomPopupOnWindow(
            isPresented: isPresented,
            style: .actionSheet,
            backgroundImage: backgroundImage,
            onDismissCompleted: onDismissCompleted // 传递回调
        ) {
            standardView
        }
    }
}

